package com.plian.system.controller.sys.excel;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.spring.SpringUtil;
import com.plian.system.annotation.Behavioral;
import com.plian.system.bean.sys.SafeProdExcelBean;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.sys.excel.AutoExcelService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "api/autoexcel")
public class AutoExcelController extends BaseController {
    @Autowired
    AutoExcelService autoExcelService;

    @Autowired
    private OrgzationService orgzationService;
/*
* 保存
* */
    @PostMapping(value = "/saveAutoExcel")
    public ObjResult saveAutoExcel(@RequestBody PageData pd) throws Exception {
        return autoExcelService.saveAutoExcel(pd);
    }
    @PostMapping(value = "/saveAutoExcelFile")
    public ObjResult saveAutoExcelFile(@RequestBody PageData pd) throws Exception {
        return autoExcelService.saveAutoExcelFile(pd);
    }
    @PostMapping(value = "/saveExcelForm")
    public ObjResult saveExcelForm(@RequestBody PageData pd) throws Exception {
        return autoExcelService.saveExcelForm(pd);
    }
    @PostMapping(value = "/saveExcelColumn")
    public ObjResult saveExcelColumn(@RequestBody PageData pd) throws Exception {
        return autoExcelService.saveExcelColumn(pd);
    }
    @PostMapping(value = "/saveExcelBill")
    public ObjResult saveExcelBill(@RequestBody PageData pd) throws Exception {
        return autoExcelService.saveExcelBill(pd);
    }
    @PostMapping(value = "/jsonToForm")
    public ObjResult jsonToForm(@RequestBody PageData pd) throws Exception {
        return autoExcelService.jsonToForm(pd);
    }

    @PostMapping(value = "/save")
    public ObjResult save(@RequestBody PageData pd) throws Exception {
        return autoExcelService.saveValue(pd);
    }
    /*
    * 列表
    *
    * */
    @PostMapping(value = "/listAutoExcel")
    public ListResult<PageData> listAutoExcel(@RequestBody PageData pd) throws Exception {
        return autoExcelService.listAutoExcel(pd);
    }
    @PostMapping(value = "/listExcelForm")
    public ListResult<PageData> listExcelForm(@RequestBody PageData pd) throws Exception {
        return autoExcelService.listExcelForm(pd);
    }
    @PostMapping(value = "/selectedExcelForm")
    public ListResult<PageData> selectedExcelForm(@RequestBody PageData pd) throws Exception {
        return autoExcelService.selectedExcelForm(pd);
    }
    @PostMapping(value = "/listExcelColumn")
    public ListResult<PageData> listExcelColumn(@RequestBody PageData pd) throws Exception {
        return autoExcelService.listExcelColumn(pd);
    }
    @PostMapping(value = "/findByCode")
    @Behavioral
    public ObjResult findByCode(@RequestBody PageData pd) throws Exception {
        return autoExcelService.findByCode(pd);
    }

    @PostMapping(value = "/list")
    public ListResult<PageData> list(@RequestBody PageData pd) throws Exception {
        return autoExcelService.listpage(pd);
    }

    /**
     * 安全隐患排查汇总表
     * @param pd
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/totalList")
    public ListResult<PageData> totalList(@RequestBody PageData pd) throws Exception {
        pd.put("orgIds",null);
        pd.put("orgId",null);
        ListResult<PageData> listpage = autoExcelService.listpage(pd);

        ListResult orgTree = orgzationService.getSubordinatePassFictitious();
        List<PageData> orgTreeList = orgTree.getList();
        String orgName;
        if(CollectionUtil.isEmpty(orgTreeList)){
            orgName = orgzationService.getNameById(TokenUtil.getTokenOrgId());
        }else {
            orgName = orgTreeList.get(0).getString("orgName");
        }
        List<String> subtreeIds = orgzationService.getSubtreeIds(orgTreeList, TokenUtil.getTokenOrgId());
        if(CollectionUtil.isEmpty(subtreeIds)) subtreeIds.add(TokenUtil.getTokenOrgId());
        PageData pageData = new PageData();
        pageData.put("orgIds",subtreeIds);
        pageData.put("code","0004");
        pageData.put("status","3");
        if(StringUtils.isNotBlank(pd.getString("reportTime"))){
            pageData.put("reportTime",pd.get("reportTime"));
        }
        ListResult<PageData> dataResult = autoExcelService.dataList(pageData);
        List<PageData> dataList = dataResult.getList();


        Map<String, List<String>> orgToIdMap = dataList.stream()
                .collect(Collectors.groupingBy(
                        p -> p.getString("reportTime"),
                        Collectors.mapping(
                                p -> p.getString("id"),
                                Collectors.toList()
                        )
                ));
        List<PageData> list = listpage.getList();
        if(CollectionUtil.isNotEmpty(list)){
            List<PageData> finalList = new ArrayList<>();
            List<PageData> ffinalList = finalList;
            orgToIdMap.forEach((k, v)->{
                PageData data = new PageData();
                data.put("orgName",orgName);
                data.put("status",3);
                data.put("reportTime",k);
                data.put("ids",v);
                ffinalList.add(data);
            });
            finalList = finalList.stream()
                    .sorted(Comparator.comparing((PageData obj) -> obj.getString("reportTime")).reversed())
                    .collect(Collectors.toList());
            listpage.setList(finalList);
        }else {
            // 判断是否国资委
            GzwProperties gzwProperties = SpringUtil.getBean(GzwProperties.class);
            String gzwOrgId = gzwProperties.getId();
            if(TokenUtil.getTokenOrgId().equals(gzwOrgId)){
                Map<String, Set<String>> orgSubToIdMap = dataList.stream()
                        .collect(Collectors.groupingBy(
                                p -> p.getString("orgId") + "_" +p.getString("reportTime"),
                                Collectors.mapping(
                                        p -> p.getString("id"),
                                        Collectors.toSet()
                                )
                        ));
                // 如果是国资委，则list放入下一级集团单位 getchildren获取下一级单位。然后重新搞一个key以reportTime和orgId的map，依次放入
                List<PageData> subList = (List<PageData>) orgTreeList.get(0).get("children");
                Map<String,PageData> existMap = new HashMap<>();
                subList.forEach(sub -> orgSubToIdMap.forEach((k, v) ->{
                    String[] split = k.split("_");
                    String orgId = split[0];
                    String reportTime = split[1];
                    if(orgzationService.isInSubtree(orgId,sub.getString("id"),orgTreeList)){
                        if(existMap.containsKey(sub.getString("id")+"_"+reportTime)){
                            PageData data = existMap.get(sub.getString("id")+"_"+reportTime);
                            Set<String> ids = (Set<String>) data.get("ids");
                            ids.addAll(v);
                            data.put("ids",ids);
                            existMap.put(sub.getString("id")+"_"+reportTime,data);
                        }else {
                            PageData data = new PageData();
                            data.put("orgId",sub.getString("id"));
                            data.put("orgName",sub.getString("orgName"));
                            data.put("status",3);
                            data.put("reportTime",reportTime);
                            data.put("ids",v);
                            existMap.put(sub.getString("id")+"_"+reportTime,data);
                        }
                    }
                }));
                List<PageData> finalList1 = list;
                existMap.forEach((k, v) -> finalList1.add(v));
                list = list.stream()
                        .sorted(Comparator.comparing((PageData obj) -> obj.getString("orgName"))
                                .thenComparing(obj -> obj.getString("reportTime")).reversed())
                        .collect(Collectors.toList());
                listpage.setList(list);
            }else {
                // 如果不是国资委，如下
                List<PageData> finalList = list;
                if(CollectionUtil.isNotEmpty(orgToIdMap)){
                    orgToIdMap.forEach((k, v) ->{
                        PageData data = new PageData();
                        data.put("orgName",orgName);
                        data.put("status",3);
                        data.put("reportTime",k);
                        data.put("ids",v);
                        finalList.add(data);
                    });
                    list = list.stream()
                            .sorted(Comparator.comparing((PageData obj) -> obj.getString("reportTime")).reversed())
                            .collect(Collectors.toList());
                    listpage.setList(list);
                }
            }
        }
        return listpage;
    }
    /**
     * 安全隐患排查汇总表-明细
     * @param pd
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/aqValueList")
    public ListResult<SafeProdExcelBean> aqValueList(@RequestBody PageData pd) throws Exception {
        return autoExcelService.aqTotalList(pd);
    }
    /*
    * 删除
    * */
    @PostMapping(value = "/deleteAutoExcel")
    public ObjResult deleteAutoExcel(@RequestBody PageData pd) throws Exception {
        return autoExcelService.deleteAutoExcel((List<String>) pd.get("ids"));
    }
    @PostMapping(value = "/deleteForm")
    public ObjResult deleteForm(@RequestBody PageData pd) throws Exception {
        return autoExcelService.deleteForm((List<String>) pd.get("ids"));
    }
    @PostMapping(value = "/deleteColumn")
    public ObjResult deleteColumn(@RequestBody PageData pd) throws Exception {
        return autoExcelService.deleteColumn((List<String>) pd.get("ids"));
    }
    @PostMapping(value = "/delete")
    public ObjResult delete(@RequestBody PageData pd) throws Exception {
        return autoExcelService.delete(pd);
    }
    @PostMapping(value = "/valueList")
    public ListResult<PageData> valueList(@RequestBody PageData pd) throws Exception {
        return autoExcelService.valuelist(pd);
    }
    @PostMapping(value = "/getLastvaluelist")
    public ListResult<PageData> getLastvaluelist(@RequestBody PageData pd) throws Exception {
        return autoExcelService.getLastvaluelist(pd);
    }
    @PostMapping(value = "/uploadFile", produces = "application/json;charset=UTF-8")
    public ObjResult uploadFile(MultipartHttpServletRequest request) throws Exception {
        return autoExcelService.uploadFile(request);
    }

    @PostMapping(value = "/exportExcel", produces = "application/json;charset=UTF-8")
    public void exportExcel(@RequestBody PageData pd ,HttpServletResponse response, OutputStream os) throws Exception {
        autoExcelService.exportExcel(pd, response, os);
    }

    @PostMapping(value = "/exportExcels", produces = "application/json;charset=UTF-8")
    public void exportExcels(@RequestBody PageData pd ,HttpServletResponse response, OutputStream os) throws Exception {
        autoExcelService.exportExcels(pd, response, os);
    }
}
